package com.socket.client;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

public class Client {
	
	private String name;
	
	private Request message;
	
	private Socket socket;
	
	private ObjectInputStream dis;
	
	private ObjectOutputStream dos;
	
	public Client(String name,Request message){
		this.name = name;
		this.message = message;
	}
	
	public Object sendRequest(){
		try {
			socket = new Socket("127.0.0.1",60000);
			
			this.dos = new ObjectOutputStream(socket.getOutputStream());
			new ClientThread(dos,name,message).start();
			
			//read server info
			try{
				this.dis = new ObjectInputStream(socket.getInputStream());
				System.out.println("start read server info!!!");
				
				//read server status
				char status = dis.readChar();
				Object value = null;
				System.out.println("read server status!!! status:"+status);
				switch(status){
					case 's' : 
						value = dis.readObject();
						break;
					case 't' :
						throw new TimeoutException("time out!!!");
				}
				
				return value;
			}catch(IOException e){
				e.printStackTrace();
			}catch(ClassNotFoundException e){
				e.printStackTrace();
			}catch(TimeoutException e){
				e.printStackTrace();
			}
			
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			try {
				if(null != dis)
					dis.close();
				if(null != dos)
					dos.close();
				if(null != socket)
					socket.close();
					
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
}
